class UserPanel {
    constructor(homeApp) {
        this.app = homeApp;
        this.usersPanel = document.getElementById('users-panel');
    }

    initUserPanel() {
        // 初始化用户面板事件
        this.bindUserEvents();
        // 如果当前激活则加载数据
        if (this.usersPanel.classList.contains('active')) {
            this.loadUsers();
        }
    }

    bindUserEvents() {
        // 绑定用户相关事件 - 修改选择器以匹配HTML结构
        const addUserBtn = document.querySelector('#users-panel .btn.primary');
        if (addUserBtn) {
            addUserBtn.addEventListener('click', () => {
                this.showAddUserModal();
            });
        }
        // 搜索功能
        const searchInput = this.usersPanel.querySelector('.search-input');
        if (searchInput) {
            searchInput.addEventListener('input', (e) => this.handleUserSearch(e));
        }
    }

    async loadUsers() {
        try {
            const response = await this.app.authenticatedFetch('/api/web/user/getAll');
            if (response && response.ok) {
                const result = await response.json();
                console.log('API响应数据:', result); // 添加日志查看实际响应格式
                // 处理API响应
                if (result.code === 200 && Array.isArray(result.data)) {
                    this.renderUsers(result.data);
                } else {
                    console.error('API返回错误:', result.msg || '未知错误');
                    this.renderUsers([]); // 显示空状态
                }
            } else {
                console.error('HTTP错误，状态码:', response.status);
                this.renderUsers([]); // 显示空状态
            }
        } catch (error) {
            console.error('加载用户列表失败:', error);
            this.renderUsers([]); // 显示空状态
        }
    }

    renderUsers(users) {
        const tbody = document.querySelector('#users-panel tbody');
        if (tbody) {
            if (!users || users.length === 0) {
                tbody.innerHTML = '<tr><td colspan="7" style="text-align: center;">暂无用户数据</td></tr>';
                return;
            }

            tbody.innerHTML = users.map(user => `
            <tr>
                <td>${user.id || ''}</td>
                <td>${user.avatar ? `<img src="${user.avatar}" alt="头像" style="max-width: 50px; max-height: 50px;">` : ''}</td>
                <td>${user.nickname || '未知用户'}</td>
                <td>${user.phone || '无手机号'}</td>
                <td>
                    <button class="btn small" onclick="homeApp.userPanel.editUser(${user.id || 0})">编辑</button>
                    <button class="btn small ${user.disabled ? 'primary' : 'danger'}" 
                            onclick="homeApp.userPanel.toggleUserDisabled(${user.id}, ${user.disabled})">
                        ${user.disabled ? '启用' : '禁用'}
                    </button>
                </td>
            </tr>
        `).join('');
        } else {
            console.error('未找到用户表格容器');
        }
    }

    handleUserSearch(e) {
        const searchTerm = e.target.value.toLowerCase();
        const userRows = document.querySelectorAll('#users-panel tbody tr');

        userRows.forEach(row => {
            const nickname = row.cells[1].textContent.toLowerCase();
            const phone = row.cells[2].textContent.toLowerCase();

            if (nickname.includes(searchTerm) || phone.includes(searchTerm)) {
                row.style.display = '';
            } else {
                row.style.display = 'none';
            }
        });
    }

    showAddUserModal() {
        // 创建添加用户模态框
        const modal = document.createElement('div');
        modal.className = 'modal';
        modal.id = 'add-user-modal';
        modal.innerHTML = `
            <div class="modal-content">
                <div class="modal-header">
                    <h3>添加用户</h3>
                    <span class="close">&times;</span>
                </div>
                <div class="modal-body">
                    <form id="add-user-form" enctype="multipart/form-data">
                        <div class="form-group">
                            <label for="user-nickname">昵称:</label>
                            <input type="text" id="user-nickname" name="nickname" required>
                        </div>
                        <div class="form-group">
                            <label for="user-phone">手机号:</label>
                            <input type="text" id="user-phone" name="phone" required>
                        </div>
                        <div class="form-group">
                            <label for="user-password">密码:</label>
                            <input type="password" id="user-password" name="password" required>
                        </div>
                        <div class="form-group">
                            <label for="user-avatar">头像:</label>
                            <input type="file" id="user-avatar" name="avatar" accept="image/*">
                            <div class="file-preview" id="user-avatar-preview"></div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn" id="cancel-add-user">取消</button>
                    <button type="submit" class="btn primary" form="add-user-form">添加</button>
                </div>
            </div>
        `;
        document.body.appendChild(modal);

        // 绑定事件
        const closeBtn = modal.querySelector('.close');
        const cancelBtn = modal.querySelector('#cancel-add-user');
        const form = modal.querySelector('#add-user-form');
        const avatarInput = modal.querySelector('#user-avatar');

        const closeModal = () => {
            if (modal && modal.parentNode) {
                modal.remove();
            }
        };

        if (closeBtn) {
            closeBtn.addEventListener('click', closeModal);
        }

        if (cancelBtn) {
            cancelBtn.addEventListener('click', closeModal);
        }

        // 图片预览功能
        if (avatarInput) {
            avatarInput.addEventListener('change', (e) => Utils.handleImagePreview(e, 'user-avatar-preview'));
        }

        // 表单提交事件
        form.addEventListener('submit', (e) => this.handleAddUserSubmit(e));

        // 显示模态框
        modal.style.display = 'block';
    }

    async handleAddUserSubmit(e) {
        e.preventDefault();

        const nickname = document.getElementById('user-nickname').value;
        const phone = document.getElementById('user-phone').value;
        const password = document.getElementById('user-password').value;
        const avatarFile = document.getElementById('user-avatar').files[0];

        // 验证必填字段
        if (!nickname.trim()) {
            alert('请输入昵称');
            return;
        }

        if (!phone.trim()) {
            alert('请输入手机号');
            return;
        }

        if (!password.trim()) {
            alert('请输入密码');
            return;
        }

        // 检查是否有文件需要上传
        if (avatarFile) {
            // 有文件时使用 FormData
            const formData = new FormData();
            formData.append('nickname', nickname.trim());
            formData.append('phone', phone.trim());
            formData.append('password', password.trim());
            formData.append('avatar', avatarFile);

            try {
                const response = await this.app.authenticatedFetch('/api/web/user/addUser', {
                    method: 'POST',
                    body: formData
                });

                const resultText = await response.text();
                let result;
                try {
                    result = JSON.parse(resultText);
                } catch (parseError) {
                    console.error('解析响应失败:', resultText);
                    throw new Error('服务器响应格式错误');
                }

                if (result.code === 200) {
                    alert('用户添加成功');
                    // 关闭模态框
                    const modal = document.getElementById('add-user-modal');
                    if (modal) {
                        modal.remove();
                    }
                    // 重新加载用户列表
                    this.loadUsers();
                } else {
                    alert('添加失败: ' + (result.msg || '未知错误'));
                }
            } catch (error) {
                console.error('添加用户失败:', error);
                alert('添加用户失败: ' + error.message);
            }
        } else {
            // 没有文件时使用 URLSearchParams
            const params = new URLSearchParams();
            params.append('nickname', nickname.trim());
            params.append('phone', phone.trim());
            params.append('password', password.trim());

            try {
                const response = await this.app.authenticatedFetch('/api/web/user/addUser', {
                    method: 'POST',
                    body: params,
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    }
                });

                const resultText = await response.text();
                let result;
                try {
                    result = JSON.parse(resultText);
                } catch (parseError) {
                    console.error('解析响应失败:', resultText);
                    throw new Error('服务器响应格式错误');
                }

                if (result.code === 200) {
                    alert('用户添加成功');
                    // 关闭模态框
                    const modal = document.getElementById('add-user-modal');
                    if (modal) {
                        modal.remove();
                    }
                    // 重新加载用户列表
                    this.loadUsers();
                } else {
                    alert('添加失败: ' + (result.msg || '未知错误'));
                }
            } catch (error) {
                console.error('添加用户失败:', error);
                alert('添加用户失败: ' + error.message);
            }
        }
    }

    editUser(userId) {
        // 获取用户信息并显示编辑模态框
        this.app.authenticatedFetch(`/api/web/user/search/${userId}`)
            .then(response => response.json())
            .then(result => {
                if (result.code === 200) {
                    const user = result.data;
                    this.showEditUserModal(user);
                } else {
                    alert('获取用户信息失败: ' + (result.msg || '未知错误'));
                }
            })
            .catch(error => {
                console.error('获取用户信息失败:', error);
                alert('获取用户信息失败: ' + error.message);
            });
    }

    showEditUserModal(user) {
        // 创建编辑用户模态框
        const modal = document.createElement('div');
        modal.className = 'modal';
        modal.id = 'edit-user-modal';
        modal.innerHTML = `
            <div class="modal-content">
                <div class="modal-header">
                    <h3>编辑用户</h3>
                    <span class="close">&times;</span>
                </div>
                <div class="modal-body">
                    <form id="edit-user-form" enctype="multipart/form-data">
                        <input type="hidden" id="user-id" name="id" value="${user.id}">
                        <div class="form-group">
                            <label for="user-nickname">昵称:</label>
                            <input type="text" id="user-nickname" name="nickname" value="${user.nickname}" required>
                        </div>
                        <div class="form-group">
                            <label for="user-phone">手机号:</label>
                            <input type="text" id="user-phone" name="phone" value="${user.phone}" required>
                        </div>
                        <div class="form-group">
                            <label for="user-password">密码(留空则不修改):</label>
                            <input type="password" id="user-password" name="password">
                        </div>
                        <div class="form-group">
                            <label for="user-avatar">头像:</label>
                            <input type="file" id="user-avatar" name="avatar" accept="image/*">
                            <div class="file-preview" id="user-avatar-preview">
                                ${user.avatar ? `<img src="${user.avatar}" style="max-width: 200px; max-height: 200px; margin-top: 10px;" alt="当前头像">` : ''}
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn" id="cancel-edit-user">取消</button>
                    <button type="submit" class="btn primary" form="edit-user-form">更新</button>
                </div>
            </div>
        `;
        document.body.appendChild(modal);

        // 绑定事件
        const closeBtn = modal.querySelector('.close');
        const cancelBtn = modal.querySelector('#cancel-edit-user');
        const form = modal.querySelector('#edit-user-form');
        const avatarInput = modal.querySelector('#user-avatar');

        const closeModal = () => {
            if (modal && modal.parentNode) {
                modal.remove();
            }
        };

        if (closeBtn) {
            closeBtn.addEventListener('click', closeModal);
        }

        if (cancelBtn) {
            cancelBtn.addEventListener('click', closeModal);
        }

        // 图片预览功能
        if (avatarInput) {
            avatarInput.addEventListener('change', (e) => Utils.handleImagePreview(e, 'user-avatar-preview'));
        }

        // 表单提交事件
        form.addEventListener('submit', (e) => this.handleEditUserSubmit(e));

        // 显示模态框
        modal.style.display = 'block';
    }

    async handleEditUserSubmit(e) {
        e.preventDefault();

        const id = document.getElementById('user-id').value;
        const nickname = document.getElementById('user-nickname').value;
        const phone = document.getElementById('user-phone').value;
        const password = document.getElementById('user-password').value;
        const avatarFile = document.getElementById('user-avatar').files[0];

        // 验证必填字段
        if (!nickname.trim()) {
            alert('请输入昵称');
            return;
        }

        if (!phone.trim()) {
            alert('请输入手机号');
            return;
        }

        // 使用 FormData 上传数据
        const formData = new FormData();
        formData.append('id', id);
        formData.append('nickname', nickname.trim());
        formData.append('phone', phone.trim());
        
        // 只有当密码不为空时才添加到表单中
        if (password.trim()) {
            formData.append('password', password.trim());
        }
        
        // 添加头像文件和裁剪尺寸
        if (avatarFile) {
            formData.append('avatar', avatarFile);
            // 设置头像裁剪尺寸
            formData.append('avatarWidth', 200);
            formData.append('avatarHeight', 200);
        }

        try {
            const response = await this.app.authenticatedFetch('/api/web/user/updateUser', {
                method: 'POST',
                body: formData
            });

            const resultText = await response.text();
            let result;
            try {
                result = JSON.parse(resultText);
            } catch (parseError) {
                console.error('解析响应失败:', resultText);
                throw new Error('服务器响应格式错误');
            }

            if (result.code === 200) {
                alert('用户更新成功');
                // 关闭模态框
                const modal = document.getElementById('edit-user-modal');
                if (modal) {
                    modal.remove();
                }
                // 重新加载用户列表
                this.loadUsers();
            } else {
                alert('更新失败: ' + (result.msg || '未知错误'));
            }
        } catch (error) {
            console.error('更新用户失败:', error);
            alert('更新用户失败: ' + error.message);
        }
    }

    async toggleUserDisabled(userId, currentStatus) {
        try {
            const response = await this.app.authenticatedFetch(`/api/web/user/toggleDisabled/${userId}?disabled=${!currentStatus}`, {
                method: 'POST'
            });

            const resultText = await response.text();
            let result;
            try {
                result = JSON.parse(resultText);
            } catch (parseError) {
                console.error('解析响应失败:', resultText);
                throw new Error('服务器响应格式错误');
            }

            if (result.code === 200) {
                alert(result.msg || '操作成功');
                // 重新加载用户列表
                this.loadUsers();
            } else {
                alert('操作失败: ' + (result.msg || '未知错误'));
            }
        } catch (error) {
            console.error('切换用户状态失败:', error);
            alert('切换用户状态失败: ' + error.message);
        }
    }

    async deleteUser(userId) {
        try {
            const response = await this.app.authenticatedFetch(`/api/web/user/deleteUser/${userId}`, {
                method: 'DELETE'
            });

            const resultText = await response.text();
            let result;
            try {
                result = JSON.parse(resultText);
            } catch (parseError) {
                console.error('解析响应失败:', resultText);
                throw new Error('服务器响应格式错误');
            }

            if (result.code === 200) {
                alert('用户删除成功');
                // 重新加载用户列表
                this.loadUsers();
            } else {
                alert('删除失败: ' + (result.msg || '未知错误'));
            }
        } catch (error) {
            console.error('删除用户失败:', error);
            alert('删除用户失败: ' + error.message);
        }
    }
}